<template>
  <div id="app">
    <h2>{{ message }}</h2>
    <el-upload
      action
      accept=".xlsx, .xls"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handle"
    >
      <el-button type="primary">打开excel</el-button>
    </el-upload>

    <div id="output"></div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import * as XLSX from "xlsx/xlsx.mjs";

const message = ref(" XLSX 的使用");
const readFile = (file) => {
  return new Promise((resolve) => {
    let reader = new FileReader();
    reader.readAsBinaryString(file); //以二进制的方式读取
    reader.onload = (ev) => {
      resolve(ev.target.result);
    };
  });
};
const handle = async (ev) => {
  let file = ev.raw;
  console.log(file);
  if (!file) {
    console.log("文件打开失败");
    return;
  } else {
    let data = await readFile(file);
    let workbook = XLSX.read(data, { type: "binary" }); //解析二进制格式数据
    const sheetName = workbook.SheetNames[0];
    const sheet = workbook.Sheets[sheetName];
    const merges = sheet["!merges"] || [];
    console.log("sheet", sheet);
    console.log("二进制数据的解析:");
    console.log(workbook);
    let worksheet = workbook.Sheets[workbook.SheetNames[0]]; //获取第一个Sheet
    let result1 = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); //json数据格式
    let result2 = XLSX.utils.sheet_to_json(worksheet); //json数据格式
    console.log("最终解析的 json 格式数据格式1:");
    console.log(result1);
    console.log("最终解析的 json 格式数据格式2:");
    console.log(result2);

    // let html = '<table border="1" style="border-collapse: collapse;">';
      let html = '<table border="1">';

    result1.forEach((row, rowIndex) => {
      html += "<tr>";
      row.forEach((cell, colIndex) => {
        let isMerged = false;
        for (let merge of merges) {
          if (merge.s.r === rowIndex && merge.s.c === colIndex) {
            let rowspan = merge.e.r - merge.s.r + 1;
            let colspan = merge.e.c - merge.s.c + 1;
            html += `<td rowspan="${rowspan}" colspan="${colspan}">${
              cell || ""
            }</td>`;
            isMerged = true;
            break;
          }
          // 跳过合并范围内的重复单元格
          if (
            rowIndex >= merge.s.r &&
            rowIndex <= merge.e.r &&
            colIndex >= merge.s.c &&
            colIndex <= merge.e.c
          ) {
            isMerged = true;
            break;
          }
        }
        if (!isMerged) {
          html += `<td>${cell || ""}</td>`;
        }
      });
      html += "</tr>";
    });

    html += "</table>";
    document.getElementById("output").innerHTML = html;
  }
};
</script>
